// authors: Wei Chen, Yu Qiao, Igor
function Point(state,city,lat,lon,numOfTweets,tweetText){
	this.state=state;
	this.city=city;
	this.lat=lat;
	this.lon=lon;
	this.numOfTweets=numOfTweets;
	this.tweetText=tweetText;
}

var markers;
var bounds =null;
var keywordLst=null;

//construct query string from the user inputs in the form.
function getQueryString(){
	var para="";
	keywordLst=null;
	if(document.getElementById("checkKeyword").checked==false 
		&& document.getElementById("checkLocation").checked==false){
		alert("Please choose at least one of the following search options.");
		return;
	}else{
		var value=null;
		if(document.getElementById("checkKeyword").checked==true){
			if((value=document.getElementById("keywordList").value)!=""){
				para+="keywords="+value;
				keywordLst=value.split(",");
			}
		} 
		if(document.getElementById("checkLocation").checked==true){
			
			if((value=document.getElementById("locationList").value)!=""){
				//alert(value);
				if(para!=""){
					para+="&locations="+value;
				}else{
					para="locations="+value;
				}
			}
		}
	}
	if(para==""){
		alert("Please fill in at least one of the following search text area.");
	}
	return para;
}

//Ajax search function. Get the number of tweets may be retrieved.
function search(){
    document.getElementById("resultContainer").innerHTML="Searching twitter database...";
	map.clearOverlays();
	markers=[];
	var para=getQueryString();
	GDownloadUrl("SearchServlet?"+para+"&option", function(data, responseCode) {
		  if(responseCode == 200) {
			  var xml = GXml.parse(data);
			  var count = xml.documentElement.getElementsByTagName("count")[0].textContent;
			  if(count>400){
				  document.getElementById("resultContainer").innerHTML+=count+" results found. " +
			  		"Only the most recent 400 records will be returned. " +
			  		"Loading...Wait for about "+400/200+" seconds";
			  }else{
				  document.getElementById("resultContainer").innerHTML+=count+" results returned. " +
			  		"Loading...Wait for about "+count/200+" seconds";
			  }
			  loadData(para);
		  } else if(responseCode == -1) {
		    alert("Data request timed out. Please try later.");
		  } else { 
		    alert("No results returned.");
		    document.getElementById("resultContainer").innerHTML="No results yet...";
		  }
	});
}

//Ajax load data function. Get the actual number of tweets.
function loadData(para) {
	GDownloadUrl("SearchServlet?"+para, function(data, responseCode) {
		  // To ensure against HTTP errors that result in null or bad data,
		  // always check status code is equal to 200 before processing the
			// data
		/*state		city	# of tweets 	first 5 tweets*/
		  if(responseCode == 200) {
		    var xml = GXml.parse(data);
		    	    
		    var states = xml.documentElement.getElementsByTagName("state");
		    //alert(states.length);
		    if(states==null){
		    	alert("No tweets retrieved!");
		    	return;
		    }
		    var points=[];
		    for (var i = 0; i < states.length; i++) {
		    	var locations=states[i].getElementsByTagName("location");
		    	for(var j=0;j<locations.length;j++){
		    		var tweets=locations[j].getElementsByTagName("tweet");
		    		var tweetTexts=[];
		    		for(var k=0;k<tweets.length;k++){
		    			tweetTexts.push((k+1).toString()+"."+tweets[k].textContent);
		    		}
		    		point=new Point(states[i].getAttribute("name"),
		    				locations[j].getAttribute("city"),
		    				locations[j].getAttribute("lat"), 
		    				locations[j].getAttribute("lon"), 
		    				tweets.length);
		    		var text;
		    		if(tweetTexts.length>100){
		    			text=tweetTexts.slice(0,100).join("<br/>");
		    		}else{
		    			text=tweetTexts.join("<br/>");
		    		}
		    		//alert(keywordLst.length);
		    		//var o="ohio";
		    		if(keywordLst!=null){
		    			for(var k=0;k<keywordLst.length;k++){
		    				//var pattern="[^a-z]("+keywordLst[k]+")[^a-z]";
		    				//alert(pattern);
		    				var re = new RegExp(keywordLst[k],"gi");
		    				text=text.replace(re, 
		    						"<span style='color:red'>"+keywordLst[k]+"</span>");
		    				//alert(text);
		    			}
	    			}
	    			point.tweetText=text;
		    		points.push(point);
		    	}
		    }
		    points.sort(compare);
			createTable(points);
			drawMarkers(points);
		  } else if(responseCode == -1) {
		    alert("Data request timed out. Please try later.");
		  } else { 
		    alert("No results returned.");
		    document.getElementById("resultContainer").innerHTML="No results returned.";
		  }
		});
}

//Draw markers on Google Maps.
function drawMarkers(points){
	var maxNumOfTweets=0,sumNumOfTweets=0;
    for(var i=0;i<points.length;i++){
    	//alert(points[i].city);
    	sumNumOfTweets+=points[i].numOfTweets;
    	if(points[i].numOfTweets>maxNumOfTweets){
	    	maxNumOfTweets=points[i].numOfTweets;
    	}
    }
    //alert(sumNumOfTweets);
    var tweetPercentages=[];
    for(var i=0;i<points.length;i++){
    	//alert(points[i].city);
    	tweetPercentages.push(points[i].numOfTweets*1.0/sumNumOfTweets);
    }
    //alert(tweetPercentages.join(","));
	bounds= new GLatLngBounds();
    for(var i=0;i<points.length;i++){
    	var point=points[i];
    	var latlon = new GLatLng(parseFloat(point.lat),parseFloat(point.lon));
		bounds.extend(latlon);
		var html = "<div class='info'>"+point.city+","+point.state+"<br/>"
			+point.lat+ "," +point.lat
			+ "<br/># of tweets:"+ point.numOfTweets+"</div>";
        var title=point.city;
        var ratio=point.numOfTweets*1.0/maxNumOfTweets;
	    //alert(latlon.lat()+" "+latlon.lng());
	    //exit(0);
        var marker = createMarker(latlon, html, title, createIcon(ratio));
		map.addOverlay(marker);
		markers.push(marker);
    }
	map.setCenter(bounds.getCenter(),map.getBoundsZoomLevel(bounds));
	//alert(map.getBoundsZoomLevel(bounds));
	//adjustTable(document.getElementById("theOnlyTable"),tweetPercentages);
}

//Create the table of tweets.
function createTable(points){
	var div=document.createElement("div");
    var resultTable=document.createElement("table");
    resultTable.id="theOnlyTable";
    div.appendChild(resultTable);
    div.style.height=document.getElementById("resultContainer").clientHeight-10;
    div.style.overflow="auto";
    //alert(div.style.height+div.style.overflow);
    document.getElementById("resultContainer").appendChild(div);
    var tbody=document.createElement("tbody");
    //resultTable.style.height=document.getElementById("resultContainer").clientHeight;
    resultTable.appendChild(tbody);
    var tr=document.createElement("tr");
    tbody.appendChild(tr);
    var th=document.createElement("th");
    th.style.width="40px";
    th.innerHTML="State";
    tr.appendChild(th);
    
    th=document.createElement("th");
    th.style.width="40px";
    th.innerHTML="City";
    tr.appendChild(th);
    
    th=document.createElement("th");
    th.style.width="50px";
    th.innerHTML="#OfTweets";
    tr.appendChild(th);
    
    th=document.createElement("th");
    th.style.width=document.getElementById("resultContainer").width-130;
    th.innerHTML="DetailedTweets";
    tr.appendChild(th);
	for(var i=0;i<points.length;i++){
		tr=document.createElement("tr");
		tr.setAttribute("valign","top");
		tr.setAttribute("index",i);
		td=document.createElement("td");
		td.innerHTML=points[i].state;
		tr.appendChild(td);

		td=document.createElement("td");
		td.innerHTML=points[i].city;
		tr.appendChild(td);
		
		td=document.createElement("td");
		td.innerHTML=points[i].numOfTweets;
		tr.appendChild(td);

		td=document.createElement("td");
		var div=document.createElement("div");
		div.style.overflow="auto";
		div.margin="0px";
		div.innerHTML=points[i].tweetText;
		td.appendChild(div);
		tr.appendChild(td);
		GEvent.addDomListener(tr, 'click', 
				function() { 
                GEvent.trigger(markers[this.getAttribute("index")], 'click'); 
        }); 
		GEvent.addDomListener(tr, 'mouseover', function(){
			this.style.backgroundColor="#ff6";
		}); 
		GEvent.addDomListener(tr, 'mouseout', function(){
			this.style.backgroundColor="#ffc";
		}); 
		tbody.appendChild(tr);
	};
}

//Adjust the look of the result table.
function adjustTable(thisTable,tweetPercentages){
	//alert(tweetPercentages.length);
	var resultContainer=document.getElementById("resultContainer");
	var minHeight=1000;
	var trs=thisTable.getElementsByTagName("tbody")[0].getElementsByTagName("tr");
	for(var i=1;i<trs.length;i++){
		if(trs[i].offsetHeight<minHeight){
			minHeight=trs[i].offsetHeight;
		}
	}

	//alert(thisTable.offsetHeight+","+trs.length);
	//trs=trs.splice(1,trs.length);
	//alert(minHeight);
	for(var i=1;i<trs.length;i++){
		//alert(trs[i].style.height);
		var div=trs[i].getElementsByTagName("td")[3].getElementsByTagName("div")[0];
		div.style.height=(resultContainer.clientHeight-trs[0].offsetHeight-minHeight-80)*tweetPercentages[i-1]+minHeight;
		//alert(tweetPercentages[i-1]);
		//alert(trs[i].style.height+","+trs[i].offsetHeight+","+trs[i].clientHeight);
		
	}
}

//crate marker.
function createMarker(latlon, html, title, icon)
{
    var marker = new GMarker(latlon, {
        title: title,
        icon: icon
    });
    GEvent.addListener(marker, 'click', function ()
    {
        this.openInfoWindowHtml(html);
    });
	return marker;
}

//create icon.
function createIcon(ratio)
{
	//alert("ratio is "+ratio);
	var maxRadius=50;
	var minRadius=10;
    var icon = new GIcon();
    icon.image = "img/circle.png";
	//default size 20x34
    var radius=(maxRadius-minRadius)*ratio+minRadius;
    icon.iconSize = new GSize(radius, radius);
    icon.iconAnchor = new GPoint(radius/2, radius/2);
    icon.infoWindowAnchor = new GPoint(radius/2, radius/2);
    icon.infoShadowAnchor = new GPoint(radius/2, radius/2);
    return icon;
}

//sort tweets by count.
function compare(a,b) {
	if (a.numOfTweets > b.numOfTweets)
		return -1;
	if (a.numOfTweets < b.numOfTweets)
		return 1;
	return 0;
}
var map;
function init(){
	adjustWindow();
	map = new GMap2(document.getElementById("map"));
	var columbus=new GLatLng(39.966596, -83.009377);
    map.setCenter(columbus,10);
	map.setMapType(G_PHYSICAL_MAP);
	map.addControl(new GMenuMapTypeControl()); 
	map.addControl(new GScaleControl()); 
	map.addControl(new GOverviewMapControl());
	map.enableScrollWheelZoom();
	map.enableGoogleBar();
	map.openInfoWindowHtml(columbus, "<div class='info'>Hello world~</div>");
	map.addControl(new GSmallMapControl()); 
}

//adjust the look of the DOM container.
function adjustWindow(){
	var heighCompressRatio=0.1;
	var widthCompressRatio=0.05;
	var maxHeight = document.body.clientHeight*(1-heighCompressRatio);
	var maxWidth = document.body.clientWidth*(1-widthCompressRatio);
	var dividentRatio=0.4;
	var divLeftPanel = document.getElementById('leftPanel');
	var divMap = document.getElementById('map');
//	/var marginLeft=10;
	divLeftPanel.style.width = maxWidth * dividentRatio;
	divLeftPanel.style.height=maxHeight;
	//divRightPanel.style.marginLeft=maxWidth * dividentRatio+marginLeft;
	divMap.style.height = maxHeight-document.getElementById("inputContainer").clientHeight-5;
	divMap.style.width = document.getElementById("leftPanel").offsetWidth-10;
/*	if(navigator.userAgent.search('Firefox')!=-1){

	}else if(navigator.userAgent.search('Safari')!=-1 || navigator.userAgent.search('Chrome')!=-1){

	}else if(navigator.userAgent.search('MSIE')!=-1){

	}   */
	var resultContainer=document.getElementById('resultContainer');
	//alert(maxWidth+","+divLeftPanel.style.width);
	resultContainer.style.width=maxWidth-parseInt(divLeftPanel.style.width);
	resultContainer.style.height=maxHeight;
	//alert(resultContainer.style.width+","+resultContainer.style.height);
}


